//深拷贝

function deepCopy(object) {
  let result = Array.isArray(object) ? [] : {};

  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      const element = object[key];
      //判断是不是对象类型
      if (typeof element === "object" && element !== null) {
        result[key] = deepCopy(element);
      } else {
        //基本数据类型直接赋值
        result[key] = element;
      }
    }
  }
  return result;
}
var obj1 = {
  name: "libing",
  favs: [1, 2, 3, 4],
  null: null,
  xiayi: {
    cun: "lishuanglou",
  },
};

const result = deepCopy(obj1);
result.name = "李铁兵";
console.log(result);

console.log(obj1);

function deepClone1(object) {
  let result = Array.isArray(object) ? [] : {};
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      const element = object[key];
      if (typeof element === "object" && element !== null) {
        result[key] = deepClone1(element);
      } else {
        result[key] = element;
      }
    }
  }
}


/**
 * 深拷贝
 * @param obj obj
 * @param map weakmap 为了避免循环引用
 */
export function cloneDeep(obj, map = new WeakMap()) {
  if (typeof obj !== 'object' || obj == null) return obj

  // 避免循环引用
  const objFromMap = map.get(obj)
  if (objFromMap) return objFromMap

  let target = {}
  map.set(obj, target)

  // Map
  if (obj instanceof Map) {
    target = new Map()
    obj.forEach((v, k) => {
      const v1 = cloneDeep(v, map)
      const k1 = cloneDeep(k, map)
      target.set(k1, v1)
    })
  }

  // Set
  if (obj instanceof Set) {
    target = new Set()
    obj.forEach(v => {
      const v1 = cloneDeep(v, map)
      target.add(v1)
    })
  }

  // Array
  if (obj instanceof Array) {
    target = obj.map(item => cloneDeep(item, map))
  }

  // Object
  for (const key in obj) {
    const val = obj[key]
    const val1 = cloneDeep(val, map)
    target[key] = val1
  }

  return target
}
